/*
 * @Author: your name
 * @Date: 2022-01-14 15:15:14
 * @LastEditTime: 2022-01-24 23:21:49
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue-element-admin\src\utils\request.js
 */
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from "@/router"
// import axiosRetry from 'axios-retry';
// create an axios instance




// 请求之间用指数后退形式的重试延迟
// axiosRetry(axios, { retryDelay: axiosRetry.exponentialDelay});

// // 自定义重试延迟
// axiosRetry(axios, { retryDelay: (retryCount) => {
//     return retryCount * 1000;
// }});

axios.defaults.withCredentials = false
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// axiosRetry(service, {
//   retries: 2,                       // 设置自动发送请求次数
//   retryDelay: (retryCount) => {
//     return retryCount * 1000;      // 重复请求延迟
//   },
//   shouldResetTimeout: true,       //  重置超时时间
//   retryCondition: (error) => {
//     //true为打开自动发送请求，false为关闭自动发送请求
//     // console.log(error.message)
//     if (error.message.includes("timeout") || error.code === 'ECONNABORTED' || error.message === "Network Error" ) {
//       return true;
//     } else {
//       return false;
//     };
//   }
// });
// request interceptor
service.interceptors.request.use(   //请求前
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['CRM-TOKEN'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(  //请求后
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.

    if (res.code !== 200) {

      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === -1) {
        //登录已过期


        // to re-login
        // MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
        //   confirmButtonText: 'Re-Login',
        //   cancelButtonText: 'Cancel',
        //   type: 'warning'
        // }).then(() => {

        store.dispatch('user/resetToken').then(() => {
          // location.reload()
          // $router
          router.push({ path: '/login' })
        })



        // })
      }
      if (res.code == 100) {
        return Promise.resolve(res)
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // console.log('err' + error) // for debug
    console.error(error);
    // console.log(error)

    if (error.code === 'ECONNABORTED' || error.message === "Network Error" || error.message.includes("timeout")) {
      Message({
        message: '请求超时，请重试',
        type: "error",
        duration: 5 * 1000,
      })
    } else {
      Message({
        message: onRejected(error.response),
        type: 'error',
        duration: 5 * 1000
      })
    }
    // return Promise.reject(error)
    return Promise.resolve(error)

  }
)


function onRejected(response) {

  switch (response.status) {
    case 400:
      return "参数异常";
    case 404:
      return '接口不存在';
    case 403:
      return '权限错误';
    case 500:
      return '服务器错误';
    case 504:
      return '服务器宕机';
    default:
      return '未知状态码错误';
  }

}

export default service
